package org.example.interceptor;

import org.example.domain.User;
import org.example.service.imp.RedisServiceImp;
import org.example.util.HutoolUtil;
import org.example.util.UserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 这个拦截器主要处理 记录用户每天的访问情况
 *
 * 目前就处理两个访问情况
 * uv(unique visitor)每日唯一访问  记录访问项目的每一个 ip
 * dau(daily active user) 每日活跃用户 记录访问的 id
 */
@Component
public class VisitorInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisServiceImp redisServiceImp;
    @Autowired
    private UserThreadLocalUtil userThreadLocalUtil;
    @Autowired
    private HutoolUtil hutoolUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //存储uv  需要ip
        String ip = request.getRemoteHost();
        String curr = hutoolUtil.currDateToString();
        redisServiceImp.saveUniqueVisitorUser(curr+"-uv",ip);
        //存储dau 需要登录 获取id
        User user = userThreadLocalUtil.get();
        if (user!=null){
            redisServiceImp.saveDailyActiveUser(curr+"-dau",user.getId());
        }
        return true;
    }
}
